package com.five.second_shop.controller.User;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.five.second_shop.entity.*;

import com.five.second_shop.service.*;
import com.five.second_shop.util.GetCode;
import com.five.second_shop.util.JustMail;
import com.five.second_shop.util.KeyUtil;
import com.five.second_shop.util.StatusCode;
import com.five.second_shop.vo.LayuiPageVo;
import com.five.second_shop.vo.ResultVo;
import com.five.second_shop.entity.UserInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Controller
public class UserController {
    @Autowired
    private MailService mailService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;
    //导入模板引擎
    @Autowired
    private TemplateEngine templateEngine;
    /**邮箱号和注册验证码map集合*/
    private static Map<String, String> mailcodemap = new HashMap<>();

    /**
     * 注册之后弹出模态框 请求完善信息
     * @param session
     * @param modelMap
     * @return
     */
    @GetMapping("/user/perfectinfo")
    public String perfectinfo(HttpSession session, ModelMap modelMap){
        String  userid = (String) session.getAttribute("userid");
        UserInfo userInfo = userInfoService.LookUserinfo(userid);
        modelMap.put("perfectinfo",userInfo);
        return "/user/perfectinfo";
    }

    /**
     * 上传用户头像
     * @param file
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/user/updateuimg")
    @ResponseBody
    public JSONObject updateuimg (@RequestParam(value = "file",required = false)MultipartFile file, HttpSession session) throws IOException {
        JSONObject res = new JSONObject();
        JSONObject resUrl = new JSONObject();
        //uuid 随机得到上传的文件名
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());//获得文件扩展名
        String filenames = filename + "." + ext;//文件全名
        String pathname = "D:\\campusshops\\file\\" + filenames;
        file.transferTo(new File(pathname));
        resUrl.put("src", "/pic/"+filenames);
        res.put("msg", "");
        res.put("code", 0);
        res.put("data", resUrl);
        String uimgUrl = "/pic/" + filenames;
        String userid=(String) session.getAttribute("userid");
        UserInfo userInfo = new UserInfo().setUserid(userid).setUimage(uimgUrl);
        userInfoService.UpdateUserInfo(userInfo);
        return res;
    }


    /**
     * 修改个人信息
     * 1.前端传入用户昵称（username）、用户邮箱（email）、性别（sex）、学校（school）、院系（faculty）、入学时间（startime）
     * 2.前端传入变更后的字段，未变更的不传入后台
     * 3.判断更改的用户名是否已存在
     * 4.修改个人信息
     */
    @ResponseBody
    @PostMapping("/user/updateinfo")
    public ResultVo updateInfo(@RequestBody UserInfo userInfo, HttpSession session) {
        String username = userInfo.getUsername();
        String userid = (String) session.getAttribute("userid");
        Login login = new Login();
        //如果传入用户名
        if (!StringUtils.isEmpty(username)){
            login.setUsername(username);
            Login login1 = loginService.userLogin(login);
            //如果该用户名对应有用户
            if (!StringUtils.isEmpty(login1)){
                return new ResultVo(false, StatusCode.ERROR, "该用户名已存在");
            }
            login.setUserid(userid);
            //修改登录表中用户名
            loginService.updateLogin(login);
        }
        userInfo.setUserid(userid);
        Integer integer1 = userInfoService.UpdateUserInfo(userInfo);
        if (integer1 == 1) {
            return new ResultVo(true, StatusCode.OK, "修改成功");
        }
        return new ResultVo(false, StatusCode.ERROR, "修改失败");
    }

    /**
     * 展示个人信息
     */
//    @RequiresPermissions("user:userinfo") 校验用户权限 最后再做
    @GetMapping("/user/lookinfo")
    public String lookinfo(HttpSession session, ModelMap modelMap) {
        String userid = (String) session.getAttribute("userid");
        UserInfo userInfo = userInfoService.LookUserinfo(userid);
        modelMap.put("userInfo",userInfo);
        return "/user/userinfo";
    }


    /**
     * 展示用户头像昵称
     */
    @ResponseBody
    @PostMapping("/user/avatar")
    public ResultVo userAvatar( HttpSession session) {
        String userid = (String) session.getAttribute("userid");
        UserInfo userInfo = userInfoService.queryPartInfo(userid);
        return new ResultVo(true, StatusCode.OK, "查询头像成功",userInfo);
    }

    /**
     * 修改密码
     * 1.前端传入旧密码（oldpwd）、新密码（newpwd）
     * 2.判断输入旧密码和系统旧密码是否相等
     * 4.修改密码
     */
    @ResponseBody
    @PutMapping("/user/updatepwd")
    public ResultVo updatepwd(HttpSession session,@RequestBody String request) throws IOException {
        HashMap map = JSON.parseObject(request, HashMap.class);
        String oldpwd = map.get("oldpwd").toString();
        String newpwd = map.get("newpwd").toString();
        String userid = (String) session.getAttribute("userid");
        Login login = new Login();
        UserInfo userInfo = new UserInfo();
        login.setUserid(userid);
        Login login1 = loginService.userLogin(login);
        String oldpwds = new Md5Hash(oldpwd, "Campus-shops").toString();
        //如果旧密码相等
        if (oldpwds.equals(login1.getPassword())){
            //盐加密
            String passwords = new Md5Hash(newpwd, "Campus-shops").toString();
            login.setPassword(passwords);
            userInfo.setPassword(passwords).setUserid(login1.getUserid());
            Integer integer = loginService.updateLogin(login);
            Integer integer1 = userInfoService.UpdateUserInfo(userInfo);
            if (integer == 1 && integer1 == 1) {
                return new ResultVo(true, StatusCode.OK, "修改密码成功");
            }
            return new ResultVo(false, StatusCode.ERROR, "修改密码失败");
        }
        return new ResultVo(false, StatusCode.LOGINERROR, "当前密码错误");
    }

    /**更换手机号时发送短信验证码
     * 1.判断是否为更换手机号类型验证码
     * 2.判断手机号格式是否正确
     * 3.查询账号是否存在
     * 4.发送验证码
     * */
    @ResponseBody
    @PostMapping("/user/sendUpdateMail")
    public ResultVo sendupdatephone(@RequestBody String request) throws IOException {
        HashMap map = JSON.parseObject(request, HashMap.class);
        final String email = map.get("email").toString();
        final String type = map.get("type").toString();
        Login login = new Login();
        if(!type.equals("2")){
            return new ResultVo(false,StatusCode.ACCESSERROR,"违规操作");
        }
        if (!JustMail.justMail(email)) {//判断输入的手机号格式是否正确
            return new ResultVo(false,StatusCode.ERROR,"请输入正确格式的邮箱");
        }
        //查询邮箱是否存在
        login.setEmail(email);
        Login userIsExist = loginService.userLogin(login);
        if (!StringUtils.isEmpty(userIsExist)){//若手机号已注册过
            return new ResultVo(false, StatusCode.REPERROR,"邮箱已注册");
        }
        String code = GetCode.phonecode();
        Context context = new Context();
        String subject = "二手网站验证码";
        context.setVariable("title","重绑定邮箱");
        context.setVariable("id",code);
        String emailContent = templateEngine.process("common/emailTemplate",context);
        try {
            mailService.sendHtmlMail(email,subject,emailContent);
        } catch (Exception e) {
            return new ResultVo(false,StatusCode.ERROR,"验证码发送失败");
        }
        mailcodemap.put(email,code);
        return new ResultVo(true,StatusCode.OK,"验证码发送成功！注意查收");
    }

    /**
     * 修改绑定邮箱
     * 1.获取session中userid
     * 2.修改login和userInfo中对应的手机号
     */
    @ResponseBody
    @PutMapping("/user/updatephone/{mail}/{vercode}")
    public ResultVo updatephone(@PathVariable("mail")String mail,@PathVariable("vercode")String vercode,HttpSession session) {
        String userid = (String) session.getAttribute("userid");
        String rel = mailcodemap.get(mail);
        if (StringUtils.isEmpty(rel)) {//验证码到期 或者 没发送短信验证码
            return new ResultVo(false,StatusCode.ERROR,"请重新获取验证码");
        }
        if (rel.equalsIgnoreCase(vercode)) {//验证码正确
            Login login = new Login().setUserid(userid).setEmail(mail);
            UserInfo userInfo = new UserInfo().setUserid(userid).setEmail(mail);
            Integer integer = loginService.updateLogin(login);
            Integer integer1 = userInfoService.UpdateUserInfo(userInfo);
            if (integer == 1 && integer1 == 1) {
                return new ResultVo(true, StatusCode.OK, "更换邮箱成功");
            }
            return new ResultVo(false, StatusCode.SERVERERROR, "系统错误，更换失败");
        }
        return new ResultVo(false,StatusCode.ERROR,"验证码错误");
    }

    /**
     * 添加地址
     * @param address
     * @param session
     * @return
     */
    @PutMapping("/user/insertAdd")
    @ResponseBody
    public ResultVo insertAdd(@RequestBody Address address, HttpSession session) throws IOException {
        String userid = (String) session.getAttribute("userid");
        if (userid == null){
            //重定向重新登录
            return new ResultVo(false,StatusCode.LOGINERROR,"登录信息过期，重新登录");
        }
        /**
         * 地址id不为空执行更新信息
         */
        if (!address.getId().equals("")){
            Integer integer = addressService.updateAddress(address);
            if (integer>0){
                return new  ResultVo(true,StatusCode.OK,"信息保存成功");
            }
            return  new ResultVo(false,StatusCode.SERVERERROR,"服务器错误");
        }

        String key = KeyUtil.genUniqueKey();
        /*设定不是默认收获地址*/
        address.setUserid(userid).setId(key).setDefaultAdd(1);
        if (address.getDetail()==null){
            return new ResultVo(false,StatusCode.ERROR,"输入详细地址信息");
        }

        Integer integer = addressService.insertAddress(address);
        if (integer>0){
            return new  ResultVo(true,StatusCode.OK,"信息保存成功");
        }
        return  new ResultVo(false,StatusCode.SERVERERROR,"服务器错误");
    }

    /**
     * 获取所有的地址列表
     * @param session
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/user/getAddrList")
    @ResponseBody
    public LayuiPageVo getAddrList(HttpSession session,HttpServletResponse response) throws IOException {
        String userid = session.getAttribute("userid").toString();
        if (userid ==null){
            response.sendRedirect("/login");
        }
        Address address = new Address();
        address.setUserid(userid);
        List<Address> addresses = addressService.queryAddress(address);
        return new LayuiPageVo("", 0, addresses);
    }


    /**
     * 根据id删除
     * @param id
     * @return
     */
    @GetMapping("/user/delById")
    @ResponseBody
    public ResultVo delById(String id){
        Integer integer = addressService.delById(id);
        if (integer>0){
            return new  ResultVo(true,StatusCode.OK,"删除成功");
        }
        return  new ResultVo(false,StatusCode.SERVERERROR,"服务器错误");
    }

    /**
     * 设置为默认收货地址
     * @param id
     * @param session
     * @return
     */
    @GetMapping("/user/setDefault")
    @ResponseBody
    public ResultVo setDefault(String id,HttpSession session){
        Address address = new Address();
        address.setId(id);
        List<Address> addresses1 = addressService.queryAddress(address);
        Address address1 = addresses1.get(0);
        if (address1.getDefaultAdd()==0){
            return new ResultVo(true,StatusCode.REPERROR,"默认地址，无需更改");
        }
        String userid = session.getAttribute("userid").toString();
        address = new Address();
        address.setUserid(userid);
        List<Address> addresses = addressService.queryAddress(address);
        ArrayList<Object> list = new ArrayList<>();
        for (int i = 0; i < addresses.size(); i++) {
            list.add(addresses.get(i).getId());
        }
        Integer integer1 = addressService.removeDefaultAdd(list);
        if (integer1<0){
            return  new ResultVo(false,StatusCode.SERVERERROR,"服务器错误,请稍后重试");
        }
        /*初始化*/
        address = new Address();
        address.setId(id).setDefaultAdd(0);
        Integer integer = addressService.updateAddress(address);

        if (integer>0){
            return new  ResultVo(true,StatusCode.OK,"已设置为默认地址");
        }
        return  new ResultVo(false,StatusCode.SERVERERROR,"服务器错误,请稍后重试");
    }

    /**
     * 添加到购物车
     * @param goodsid
     * @param session
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/user/addCart")
    @ResponseBody
    public ResultVo addCart(String goodsid,HttpSession session,HttpServletResponse response) throws IOException {
        String userid = session.getAttribute("userid").toString();
         /*未登录直接转跳登录界面*/
        if (userid ==null){
            response.sendRedirect("/login");
        }
        Cart cart = new Cart();
        /*根据用户id和商品id查询*/
        cart.setCommodityid(goodsid).setUserid(userid);
        List<Cart> carts = cartService.queryCart(cart);

        if (carts.size()!=0){
            return new  ResultVo(true,StatusCode.REPERROR,"该商品已添加在购物车中");
        }
        String key = KeyUtil.genUniqueKey();
        cart.setId(key).setSetupdate(new Date());
        Integer integer = cartService.InsertNew(cart);
        if (integer>0){
            return new  ResultVo(true,StatusCode.OK,"已添加到购物车");
        }
        return  new ResultVo(false,StatusCode.SERVERERROR,"服务器错误,请稍后重试");
    }

    /**
     * 查询所有个人信息
     * @param session
     * @return
     */
    @GetMapping("/user/getCartList")
    @ResponseBody
    public LayuiPageVo getCartList(HttpSession session){
        String userid = session.getAttribute("userid").toString();
        Cart cart = new Cart();
        cart.setUserid(userid);
        List<Cart> carts = cartService.queryCart(cart);
        return new LayuiPageVo<>("",0,carts);
    }

    @PostMapping("/user/checkCart")
    @ResponseBody
    public ResultVo checkCart(@RequestBody String map,HttpSession session){
        HashMap map1 = JSON.parseObject(map, HashMap.class);
        List idList = (List)map1.get("idList");
        String sumPrice = map1.get("sumPrice").toString();

        String userid = session.getAttribute("userid").toString();
        Address address = new Address();
        /*查询用户是否有默认地址 0 */
        address.setUserid(userid).setDefaultAdd(0);
        List<Address> addresses = addressService.queryAddress(address);

        if (addresses.size()==0){
            return new ResultVo(true,StatusCode.ERROR,"请在个人中心，选择默认收货地址");
        }
        Integer statue = 1;
        Order order = new Order();
        Cart cart = new Cart();
        /*勾选多选 多次循环 单选购买一次循环*/
        for (int i = 0; i < idList.size(); i++) {
            String commid = idList.get(i).toString();
            cart.setCommodityid(commid);
            String key = KeyUtil.genUniqueKey();
            order.setUserid(userid)
                    .setAddress(addresses.get(i).getId())
                    .setCommid(commid)
                    .setOrderstatus(0)
                    .setOrderid(key);
            /*新增订单*/
            Integer integer = orderService.insertOrder(order);
            /*删除购物车*/
            Integer integer1 = cartService.delCart(cart);
            statue = integer + integer1;
        }
        if (statue>0){
            return new ResultVo(true,StatusCode.OK,"正在转跳订单页面");
        }
        return new ResultVo(false,StatusCode.SERVERERROR,"服务器错误,请稍后重试");
    }
}
